// ZENrs FFI集成示例
// 这个文件展示了如何在safe_services中使用我们实现的FFI功能

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_void};
use std::sync::Arc;
use std::sync::Mutex;
use std::ptr;
use std::time::Duration;
use std::thread;
use log::{info, error};

// 导入ZENrs服务层核心
use safe_services::{ServiceManager, Capability};

// FFI相关类型定义
#[repr(C)]
struct ZenrsMessage {
    message_type: u32,
    sender_id: u64,
    target_id: u64,
    data_size: u64,
    data_ptr: *mut c_void,
}

// 增强的数据结构定义
#[repr(C)]
struct ZenrsComplexData {
    id: u64,
    name_ptr: *const c_char,
    values_count: u32,
    values_ptr: *mut u64,
    config_ptr: *mut c_void,
    is_valid: bool,
}

#[repr(C)]
struct ZenrsSharedMemory {
    buffer: *mut u8,
    size: u64,
    is_locked: bool,
    owner_id: u64,
    creation_time: u64,
}

// 错误码定义
const ZENRS_OK: i32 = 0;
const ZENRS_ERROR_INVALID_PARAM: i32 = -1;
const ZENRS_ERROR_TIMEOUT: i32 = -5;
const ZENRS_ERROR_LOCK_FAILED: i32 = -6;
const ZENRS_ERROR_CALLBACK_ERROR: i32 = -7;

// 从exokernel导入的FFI函数
#[link(name = "exokernel")]
extern "C" {
    fn zenrs_zig_get_system_info(buffer: *mut c_void, buffer_size: u64) -> i32;
    fn zenrs_zig_create_object(size: u64) -> *mut c_void;
    fn zenrs_zig_free_object(object_ptr: *mut c_void, size: u64);
    fn zenrs_zig_process_string(input: *const c_char) -> *mut c_char;
    fn zenrs_zig_free_string(str_ptr: *mut c_char);
    fn zenrs_zig_get_timestamp() -> u64;
    // 增强功能 - 从Zig导入的新函数
    fn zenrs_zig_process_with_callback(
        data: *mut c_void,
        callback: *const extern "C" fn(context: *mut c_void, result: i32, data: *mut c_void) -> i32,
        context: *mut c_void
    ) -> i32;
    fn zenrs_zig_async_operation(
        operation_id: *mut u64,
        task_data: *mut c_void,
        data_size: u64
    ) -> i32;
    fn zenrs_zig_create_shared_memory(size: u64) -> *mut ZenrsSharedMemory;
    fn zenrs_zig_free_shared_memory(memory_ptr: *mut ZenrsSharedMemory);
    fn zenrs_zig_lock_shared_memory(memory_ptr: *mut ZenrsSharedMemory, timeout_ms: u64) -> i32;
    fn zenrs_zig_unlock_shared_memory(memory_ptr: *mut ZenrsSharedMemory) -> i32;
    fn zenrs_zig_batch_process(
        items: *mut *mut c_void,
        item_count: u32,
        process_fn: *const extern "C" fn(context: *mut c_void, item: *mut c_void) -> i32,
        context: *mut c_void
    ) -> i32;
    fn zenrs_zig_create_complex_data(
        id: u64,
        name: *const c_char,
        values_count: u32,
    ) -> *mut ZenrsComplexData;
    fn zenrs_zig_free_complex_data(data_ptr: *mut ZenrsComplexData);
    fn zenrs_zig_get_last_error(buffer: *mut c_char, buffer_size: u64) -> i32;
    fn zenrs_zig_convert_data_type(
        src_data: *const c_void,
        src_type: u32,
        dst_data: *mut c_void,
        dst_type: u32,
        data_size: u64
    ) -> i32;
}

// 从我们的FFI库导入的函数
#[link(name = "zenrs_ffi")]
extern "C" {
    fn zenrs_get_version() -> *const c_char;
    fn zenrs_create_message(
        message_type: u32,
        sender_id: u64,
        target_id: u64,
        data_size: u64
    ) -> *mut ZenrsMessage;
    fn zenrs_free_message(message_ptr: *mut ZenrsMessage);
    fn zenrs_process_string(input: *const c_char) -> *mut c_char;
    fn zenrs_free_string(str_ptr: *mut c_char);
    // 增强功能 - 从Rust导入的新函数
    fn zenrs_create_complex_data(
        id: u64,
        name: *const c_char,
        values_count: u32,
    ) -> *mut ZenrsComplexData;
    fn zenrs_free_complex_data(data_ptr: *mut ZenrsComplexData);
    fn zenrs_process_with_callback(
        data: *mut c_void,
        callback: *const extern "C" fn(context: *mut c_void, result: i32, data: *mut c_void) -> i32,
        context: *mut c_void
    ) -> i32;
    fn zenrs_async_operation(
        operation_id: *mut u64,
        task_data: *mut c_void,
        data_size: u64
    ) -> i32;
    fn zenrs_cancel_async_operation(operation_id: u64) -> i32;
    fn zenrs_create_shared_memory(size: u64) -> *mut ZenrsSharedMemory;
    fn zenrs_free_shared_memory(memory_ptr: *mut ZenrsSharedMemory);
    fn zenrs_lock_shared_memory(memory_ptr: *mut ZenrsSharedMemory, timeout_ms: u64) -> i32;
    fn zenrs_unlock_shared_memory(memory_ptr: *mut ZenrsSharedMemory) -> i32;
    fn zenrs_batch_process(
        items: *mut *mut c_void,
        item_count: u32,
        process_fn: *const extern "C" fn(context: *mut c_void, item: *mut c_void) -> i32,
        context: *mut c_void
    ) -> i32;
    fn zenrs_get_last_error(buffer: *mut c_char, buffer_size: u64) -> i32;
    fn zenrs_convert_data_type(
        src_data: *const c_void,
        src_type: u32,
        dst_data: *mut c_void,
        dst_type: u32,
        data_size: u64
    ) -> i32;
}

// 扩展ServiceManager以使用FFI功能
pub struct EnhancedServiceManager {
    service_manager: Arc<Mutex<ServiceManager>>,
}

impl EnhancedServiceManager {
    // 创建新的增强型服务管理器
    pub fn new(service_manager: Arc<Mutex<ServiceManager>>) -> Self {
        EnhancedServiceManager {
            service_manager,
        }
    }
    
    // 获取系统信息
    pub fn get_system_info(&self) -> Result<String, String> {
        // 为系统信息分配缓冲区
        let mut buffer = [0u8; 1024];
        let buffer_ptr = buffer.as_mut_ptr() as *mut c_void;
        
        // 调用Zig函数获取系统信息
        let result = unsafe {
            zenrs_zig_get_system_info(buffer_ptr, buffer.len() as u64)
        };
        
        if result < 0 {
            return Err(format!("Failed to get system info, error code: {}", result));
        }
        
        // 尝试将缓冲区内容转换为字符串
        let system_info = unsafe {
            CStr::from_ptr(buffer_ptr as *const c_char)
                .to_str()
                .map_err(|e| e.to_string())?
        };
        
        Ok(system_info.to_string())
    }
    
    // 获取当前时间戳
    pub fn get_timestamp(&self) -> u64 {
        unsafe {
            zenrs_zig_get_timestamp()
        }
    }
    
    // 获取ZENrs版本信息
    pub fn get_version(&self) -> String {
        let version_ptr = unsafe {
            zenrs_get_version()
        };
        
        let version_str = unsafe {
            CStr::from_ptr(version_ptr)
                .to_str()
                .unwrap_or("Unknown version")
        };
        
        version_str.to_string()
    }
    
    // 创建一个新的消息
    pub fn create_message(&self, message_type: u32, sender_id: u64, target_id: u64, data_size: u64) -> Result<*mut ZenrsMessage, String> {
        let message_ptr = unsafe {
            zenrs_create_message(message_type, sender_id, target_id, data_size)
        };
        
        if message_ptr.is_null() {
            return Err("Failed to create message".to_string());
        }
        
        Ok(message_ptr)
    }
    
    // 释放消息
    pub fn free_message(&self, message_ptr: *mut ZenrsMessage) {
        if !message_ptr.is_null() {
            unsafe {
                zenrs_free_message(message_ptr);
            }
        }
    }
    
    // 处理字符串
    pub fn process_string(&self, input: &str) -> Result<String, String> {
        // 将Rust字符串转换为C风格字符串
        let c_input = CString::new(input).map_err(|e| e.to_string())?;
        
        // 调用Rust FFI函数处理字符串
        let processed_ptr = unsafe {
            zenrs_process_string(c_input.as_ptr())
        };
        
        if processed_ptr.is_null() {
            return Err("Failed to process string".to_string());
        }
        
        // 将结果转换回Rust字符串
        let processed_str = unsafe {
            CStr::from_ptr(processed_ptr)
                .to_str()
                .map_err(|e| e.to_string())?
        };
        
        let result = processed_str.to_string();
        
        // 释放由zenrs_process_string分配的内存
        unsafe {
            zenrs_free_string(processed_ptr);
        }
        
        Ok(result)
    }
    
    // 测试Zig的字符串处理函数
    pub fn zig_process_string(&self, input: &str) -> Result<String, String> {
        // 将Rust字符串转换为C风格字符串
        let c_input = CString::new(input).map_err(|e| e.to_string())?;
        
        // 调用Zig FFI函数处理字符串
        let processed_ptr = unsafe {
            zenrs_zig_process_string(c_input.as_ptr())
        };
        
        if processed_ptr.is_null() {
            return Err("Failed to process string with Zig".to_string());
        }
        
        // 将结果转换回Rust字符串
        let processed_str = unsafe {
            CStr::from_ptr(processed_ptr)
                .to_str()
                .map_err(|e| e.to_string())?
        };
        
        let result = processed_str.to_string();
        
        // 释放由zenrs_zig_process_string分配的内存
        unsafe {
            zenrs_zig_free_string(processed_ptr);
        }
        
        Ok(result)
    }
    
    // 测试对象创建和释放
    pub fn test_object_management(&self, size: u64) -> Result<(), String> {
        // 创建对象
        let object_ptr = unsafe {
            zenrs_zig_create_object(size)
        };
        
        if object_ptr.is_null() {
            return Err("Failed to create object".to_string());
        }
        
        info!("Created object of size {} bytes at {:p}", size, object_ptr);
        
        // 在这里可以使用对象...
        
        // 释放对象
        unsafe {
            zenrs_zig_free_object(object_ptr, size);
        }
        
        info!("Freed object of size {} bytes", size);
        
        Ok(())
    }
    
    // 增强功能：使用回调函数处理数据
    pub fn process_with_zig_callback(&self, data: &str) -> Result<i32, String> {
        // 将Rust字符串转换为C风格字符串
        let c_data = CString::new(data).map_err(|e| e.to_string())?;
        
        // 定义一个Rust闭包作为回调函数
        extern "C" fn rust_callback(context: *mut c_void, result: i32, data: *mut c_void) -> i32 {
            if !data.is_null() {
                let data_str = unsafe {
                    CStr::from_ptr(data as *const c_char)
                        .to_str()
                        .unwrap_or("Invalid data")
                };
                info!("Callback received result: {}, data: {}", result, data_str);
            }
            result
        }
        
        let result = unsafe {
            zenrs_zig_process_with_callback(
                c_data.as_ptr() as *mut c_void,
                rust_callback,
                ptr::null_mut()
            )
        };
        
        if result < 0 {
            return Err(format!("Callback processing failed with error code: {}", result));
        }
        
        Ok(result)
    }
    
    // 增强功能：创建并处理复杂数据结构
    pub fn create_and_process_complex_data(&self, id: u64, name: &str, values_count: u32) -> Result<(), String> {
        // 将Rust字符串转换为C风格字符串
        let c_name = CString::new(name).map_err(|e| e.to_string())?;
        
        // 从Zig创建复杂数据结构
        let complex_data_ptr = unsafe {
            zenrs_zig_create_complex_data(id, c_name.as_ptr(), values_count)
        };
        
        if complex_data_ptr.is_null() {
            return Err("Failed to create complex data".to_string());
        }
        
        // 访问复杂数据结构的字段
        let complex_data = unsafe { &*complex_data_ptr };
        
        info!("Created complex data: id={}, name={:?}, values_count={}, is_valid={}", 
            complex_data.id,
            unsafe { CStr::from_ptr(complex_data.name_ptr).to_str().ok() },
            complex_data.values_count,
            complex_data.is_valid
        );
        
        // 访问值数组（如果有）
        if !complex_data.values_ptr.is_null() && complex_data.values_count > 0 {
            info!("First value in complex data: {}", unsafe { *complex_data.values_ptr });
        }
        
        // 释放复杂数据结构
        unsafe {
            zenrs_zig_free_complex_data(complex_data_ptr);
        }
        
        info!("Freed complex data");
        
        Ok(())
    }
    
    // 增强功能：测试异步操作
    pub fn test_async_operation(&self, task_data: &str) -> Result<u64, String> {
        // 将Rust字符串转换为C风格字符串
        let c_task_data = CString::new(task_data).map_err(|e| e.to_string())?;
        
        let mut operation_id: u64 = 0;
        
        let result = unsafe {
            zenrs_zig_async_operation(
                &mut operation_id,
                c_task_data.as_ptr() as *mut c_void,
                task_data.len() as u64
            )
        };
        
        if result < 0 {
            return Err(format!("Failed to start async operation, error code: {}", result));
        }
        
        info!("Started async operation with ID: {}", operation_id);
        
        Ok(operation_id)
    }
    
    // 增强功能：测试共享内存
    pub fn test_shared_memory(&self, size: u64) -> Result<(), String> {
        // 创建共享内存
        let shared_memory_ptr = unsafe {
            zenrs_zig_create_shared_memory(size)
        };
        
        if shared_memory_ptr.is_null() {
            return Err("Failed to create shared memory".to_string());
        }
        
        let shared_memory = unsafe { &*shared_memory_ptr };
        info!("Created shared memory: size={}, buffer={:p}", 
            shared_memory.size, 
            shared_memory.buffer
        );
        
        // 锁定共享内存
        let lock_result = unsafe {
            zenrs_zig_lock_shared_memory(shared_memory_ptr, 1000) // 1秒超时
        };
        
        if lock_result < 0 {
            unsafe { zenrs_zig_free_shared_memory(shared_memory_ptr); }
            return Err(format!("Failed to lock shared memory, error code: {}", lock_result));
        }
        
        info!("Shared memory locked successfully");
        
        // 使用共享内存（写入一些数据）
        if !shared_memory.buffer.is_null() && shared_memory.size > 0 {
            let buffer_size = shared_memory.size as usize;
            let buffer_slice = unsafe { std::slice::from_raw_parts_mut(shared_memory.buffer, buffer_size) };
            
            // 写入测试数据
            let test_data = "ZENrs Shared Memory Test";
            let copy_len = std::cmp::min(test_data.len(), buffer_size);
            buffer_slice[..copy_len].copy_from_slice(test_data.as_bytes());
            
            info!("Wrote test data to shared memory");
        }
        
        // 解锁共享内存
        let unlock_result = unsafe {
            zenrs_zig_unlock_shared_memory(shared_memory_ptr)
        };
        
        if unlock_result < 0 {
            unsafe { zenrs_zig_free_shared_memory(shared_memory_ptr); }
            return Err(format!("Failed to unlock shared memory, error code: {}", unlock_result));
        }
        
        info!("Shared memory unlocked successfully");
        
        // 释放共享内存
        unsafe {
            zenrs_zig_free_shared_memory(shared_memory_ptr);
        }
        
        info!("Freed shared memory");
        
        Ok(())
    }
    
    // 增强功能：测试批量数据处理
    pub fn test_batch_processing(&self) -> Result<(), String> {
        // 准备一些测试数据
        let test_strings = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"];
        
        // 将Rust字符串转换为C风格字符串并存储它们的指针
        let mut c_strings = Vec::new();
        let mut item_ptrs = Vec::new();
        
        for s in test_strings.iter() {
            let c_str = CString::new(*s).map_err(|e| e.to_string())?;
            c_strings.push(c_str);
        }
        
        // 收集指针
        for c_str in c_strings.iter() {
            item_ptrs.push(c_str.as_ptr() as *mut c_void);
        }
        
        // 定义批处理回调函数
        extern "C" fn process_item_callback(context: *mut c_void, item: *mut c_void) -> i32 {
            if !item.is_null() {
                let item_str = unsafe {
                    CStr::from_ptr(item as *const c_char)
                        .to_str()
                        .unwrap_or("Invalid item")
                };
                info!("Processing item: {}", item_str);
            }
            ZENRS_OK
        }
        
        // 调用Zig的批量处理函数
        let processed_count = unsafe {
            zenrs_zig_batch_process(
                item_ptrs.as_mut_ptr(),
                item_ptrs.len() as u32,
                process_item_callback,
                ptr::null_mut()
            )
        };
        
        if processed_count < 0 {
            return Err(format!("Batch processing failed with error code: {}", processed_count));
        }
        
        info!("Successfully processed {} items", processed_count);
        
        Ok(())
    }
    
    // 增强功能：获取最后错误信息
    pub fn get_last_error(&self) -> String {
        let mut buffer = [0u8; 1024];
        
        let result = unsafe {
            zenrs_zig_get_last_error(buffer.as_mut_ptr() as *mut c_char, buffer.len() as u64)
        };
        
        if result <= 0 {
            return "No error information available".to_string();
        }
        
        let error_str = unsafe {
            CStr::from_ptr(buffer.as_ptr() as *const c_char)
                .to_str()
                .unwrap_or("Invalid error string")
        };
        
        error_str.to_string()
    }
}

// 运行FFI集成测试
pub fn run_ffi_integration_test(service_manager: Arc<Mutex<ServiceManager>>) -> Result<(), String> {
    info!("Starting FFI integration test...");
    
    // 创建增强型服务管理器
    let enhanced_manager = EnhancedServiceManager::new(service_manager);
    
    // 测试版本信息
    let version = enhanced_manager.get_version();
    info!("ZENrs version: {}", version);
    
    // 测试系统信息
    let system_info = enhanced_manager.get_system_info()?;
    info!("System info:\n{}", system_info);
    
    // 测试时间戳
    let timestamp = enhanced_manager.get_timestamp();
    info!("Current timestamp: {}", timestamp);
    
    // 测试字符串处理
    let test_str = "Hello, ZENrs!";
    let processed_str = enhanced_manager.process_string(test_str)?;
    info!("Original string: {}", test_str);
    info!("Processed string (Rust): {}", processed_str);
    
    // 测试Zig的字符串处理
    let zig_processed_str = enhanced_manager.zig_process_string(test_str)?;
    info!("Processed string (Zig): {}", zig_processed_str);
    
    // 测试消息创建和释放
    const msg_data_size = 64;
    let message_ptr = enhanced_manager.create_message(1, 100, 200, msg_data_size)?;
    info!("Created message at {:p}", message_ptr);
    
    // 释放消息
    enhanced_manager.free_message(message_ptr);
    info!("Freed message");
    
    // 测试对象管理
    enhanced_manager.test_object_management(256)?;
    
    // ===== 增强功能测试开始 =====
    
    // 测试回调函数处理
    enhanced_manager.process_with_zig_callback("Callback test data")?;
    
    // 测试复杂数据结构
    enhanced_manager.create_and_process_complex_data(123, "TestComplexData", 5)?;
    
    // 测试异步操作
    let async_op_id = enhanced_manager.test_async_operation("Async task data")?;
    info!("Async operation ID: {}", async_op_id);
    
    // 测试共享内存
    enhanced_manager.test_shared_memory(512)?;
    
    // 测试批量数据处理
    enhanced_manager.test_batch_processing()?;
    
    // 测试错误信息获取
    let last_error = enhanced_manager.get_last_error();
    info!("Last error: {}", last_error);
    
    // ===== 增强功能测试结束 =====
    
    info!("FFI integration test completed successfully!");
    
    Ok(())
}

// 在实际应用中，你可以在main.rs中调用这个测试函数
// 例如：
// 
// fn main() {
//     // ... 初始化代码 ...
//     
//     // 启动服务管理器
//     let service_manager = Arc::new(Mutex::new(service_manager));
//     
//     // 运行FFI集成测试
//     if let Err(err) = run_ffi_integration_test(service_manager.clone()) {
//         error!("FFI test failed: {}", err);
//     }
//     
//     // ... 主循环代码 ...
// }